package eHealth.android.Helpers;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 
 * @author Thomas Rouvinez
 * Date 15.03.2012
 * 
 * Goal : check input values for Integers in editText objects.
 *
 */
public class InputFilterMinMax implements InputFilter {
	
	// --------------------------------------------------------------------
	// Variables.
	// --------------------------------------------------------------------
	
	/**
	 * Integer values for minimum and maximum values. 
	 */
	private int min, max;
	 
	// --------------------------------------------------------------------
	// Constructors.
	// --------------------------------------------------------------------
	
	/**
	 * Constructor with integers min and max values.
	 * @param min
	 * @param max
	 */
	public InputFilterMinMax(int min, int max) {
		this.min = min;
		this.max = max;
	}
 
	/**
	 * Constructor with String min and max values.
	 * @param min
	 * @param max
	 */
	public InputFilterMinMax(String min, String max) {
		this.min = Integer.parseInt(min);
		this.max = Integer.parseInt(max);
	}

	// --------------------------------------------------------------------
	// Methods.
	// --------------------------------------------------------------------
	
	/**
	 * Actual filter of values.
	 */
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {	
		try {
			int input = Integer.parseInt(dest.toString() + source.toString());
			if (isInRange(min, max, input))
				return null;
		} catch (NumberFormatException nfe) { }		
		return "";
	}
	
	/**
	 * Check if value is in the specified range and that the range is valid.
	 * @param a
	 * @param b
	 * @param c
	 * @return
	 */
	private boolean isInRange(int a, int b, int c) {
		return b > a ? c >= a && c <= b : c >= b && c <= a;
	}
}